package com.wenbing.miio.core;

import java.net.SocketAddress;

/**
 * 网络接口层 上下文
 * @author wen bing
 * @projectName: miio
 * @package: core.ps
 * @className: P
 * @date 2024/09/19 11:07
 **/
public interface NetworkLayerContext extends Context {

    String LOCAL_ADDRESS = "share_local_address";

    String REMOTE_ADDRESS = "share_remote_address";

    NetworkLayerContext getParentContext();

    default SocketAddress getLocalAddress() {
        return getShareAttribute(LOCAL_ADDRESS);
    }

    default SocketAddress getRemoteAddress() {
        return getShareAttribute(REMOTE_ADDRESS);
    }

    /**
     * 共享属性操作，实现属性多层协议透传
     * @return
     */
    Context getShareContext();

    /**
     * 共享属性操作，实现属性多层协议透传
     * @param key
     * @param attr
     * @param <T>
     * @return
     */
    default <T> T getShareAttribute(String key, T attr) {
        Context context = getShareContext();
        return context == null ?
                null : context.getAttribute(key, attr);
    }

    default <T> T getShareAttribute(String key) {
        return getShareAttribute(key, null);
    }

    default void removeShareAttribute(String key) {
        Context context = getShareContext();
        if (context != null) {
            context.removeAttribute(key);
        }
    }

    void setShareAttribute(String key, Object attr);
}
